package com.xuecheng.order.mq;

import com.xuecheng.framework.domain.task.XcTask;
import com.xuecheng.framework.model.response.ResponseResult;
import com.xuecheng.order.config.RabbitMQConfig;
import com.xuecheng.order.service.XcTaskService;
import lombok.extern.slf4j.Slf4j;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.amqp.rabbit.annotation.RabbitListener;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Scheduled;
import org.springframework.stereotype.Component;

import java.util.Calendar;
import java.util.Date;
import java.util.GregorianCalendar;
import java.util.List;

/**
 * @author: gongfy
 * @create: 2020/9/24 10:00
 * @Description: 定时任务测试类
 */
@Component
public class ChooseCourseTask {

    @Autowired
    private XcTaskService xcTaskService;

    private static final Logger log = LoggerFactory.getLogger(ChooseCourseTask.class);

    //定时发送选课任务
    @Scheduled(cron = "0/3 * * * * *") //在任务开启后3秒执行下一次调度   fixedDelay:在任务结束后n秒才开始执行
    public void sendChooseCourseTask(){
        log.info("------------------------------定时发送选课消息任务开始------------------------------");
        // 获取1分钟之前的时间
        Calendar calendar = new GregorianCalendar();
        calendar.setTime(new Date());
        calendar.set(GregorianCalendar.MINUTE,-1);
        Date updateTime = calendar.getTime(); // 注意时间是系统时间还是
        //1.查询任务
        List<XcTask> xcTaskList = xcTaskService.findXcTaskByUpdateTimeBefore(updateTime, 100);
        //2.遍历任务列表 经乐观锁判断后发送
        for (XcTask xcTask : xcTaskList) {
            int i = xcTaskService.updateTaskVersion(xcTask.getId(), xcTask.getVersion());
            if (i > 0) {
                //2.发送选课消息+更新时间
                xcTaskService.sendMsgAndUpdateTime(xcTask, xcTask.getMqExchange(), xcTask.getMqRoutingkey());
                log.info("send choose course task id:{}", xcTask.getId());
            }
        }
        log.info("------------------------------定时发送选课消息任务结束------------------------------");
    }

    //接收‘完成选课任务’
    @RabbitListener(queues = RabbitMQConfig.XC_LEARNING_FINISHADDCHOOSECOURSE)
    public void  receivefinishTask(XcTask xcTask){
        //1.解析出消息中任务，将task表中任务移到task_his中
        xcTaskService.finishTask(xcTask.getId());
    }

}
